import PropTypes from 'prop-types';
import React from 'react';
import { animated, config as SpringConfig, Transition } from 'react-spring';

import classNames from 'classnames';

interface IFadeConfig {
  [key: string]: any;
}

export interface IFadeProps {
  className?: string;
  style?: React.CSSProperties;
  active: boolean;
  delay?: number;
  config?: string;
  from?: React.CSSProperties;
  enter?: React.CSSProperties;
  leave?: React.CSSProperties;
}
export class Fade extends React.Component<IFadeProps, {}> {
  public static propTypes = {
    className: PropTypes.string,
    style: PropTypes.object,
    active: PropTypes.bool,
    delay: PropTypes.number,
    config: PropTypes.oneOf(['default', 'wobbly', 'stiff', 'slow', 'molasses']),
  };

  public static defaultProps = {
    className: '',
    style: null,
    active: false,
    delay: 0,
    config: 'default',
  };

  constructor(props: IFadeProps) {
    super(props);
  }
  public render() {
    const {
      active,
      className,
      style,
      config,
      from = { opacity: 0, height: 0 },
      enter = { opacity: 1, height: 'auto' },
      leave = { opacity: 0, height: 0 },
      delay } = this.props;

    let fadeConfig: IFadeConfig = SpringConfig;

    return (
      <Transition
        native
        initial={false}
        delay={delay}
        config={{
          ...fadeConfig[`${config}`],
        }}
        items={+active}
        keys={String(active)}
        from={from}
        enter={enter}
        leave={leave}>
        {
          (isActive) => isActive && ((styles: React.CSSProperties) =>
            <animated.div style={{
              ...styles,
              ...style,
            }}>
              <div className={classNames('br-fade', className)}>
                {this.props.children}
              </div>
            </animated.div>)
          }
        </Transition>
    );
  }
}
